package helpers;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import entities.KeywordRanking;

public class CrawlerHelper {
	public static KeywordRanking getKeywordRanking(KeywordRanking keywordRanking) {
		String url = "http://www.statscrop.com/keyword-ranking-analysis/domain/" + keywordRanking.getDomain();
		
		try {
			Document doc = Jsoup.connect(url).get();
			
			String chartJs = "";
			Elements elms = doc.select("script");
			for (int i = 0; i < elms.size(); i++) {
				if (elms.get(i).html().contains("chart_div_line")) {
					chartJs = elms.get(i).html();
				}
			}
			
			String positionContent = doc.select("#innercontent div.clear:contains(Position 1)").html();
			String best1position = doc.select("#innercontent:contains(Best of 1 positions) > div").html();
			best1position = best1position.replaceAll("[<]{1}(a)[^>]+[>]{1}", "").replaceAll("<\\/a>", "");
			String best2positions = doc.select("#innercontent:contains(Best of 2) > div").html();
			best2positions = best2positions.replaceAll("[<]{1}(a)[^>]+[>]{1}", "").replaceAll("<\\/a>", "");
			String best10positions = doc.select("#innercontent:contains(Best of 6) > div").html();
			best10positions = best10positions.replaceAll("[<]{1}(a)[^>]+[>]{1}", "").replaceAll("<\\/a>", "");
			
			keywordRanking.setChartJs(chartJs);
			keywordRanking.setPositionContent(positionContent);
			keywordRanking.setBest1position(best1position);
			keywordRanking.setBest10positions(best10positions);
			keywordRanking.setBest2positions(best2positions);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		return keywordRanking;
	}
}
